from django.shortcuts import render
from utils.pager import Pagination
from django.db.models import Q
from web import models
from utils.group import Option, NbSearchGroup


def my_transaction_list(request):
    """我的交易记录"""
    # 配置
    from utils.group import Option, NbSearchGroup
    search_group = NbSearchGroup(request, models.TransactionRecord, Option('charge_type'))  # choice
    # 也可以 Option('charge_type', is_multi=True, text_func=lambda x: x[1], value_func=lambda x: x[0]),  # choice
    # Option('customer', db_condition={'active': 1}, text_func=lambda x: x.username,
    #        value_func=lambda x: x.id),  # foreignkey

    # search_group_row_list = []
    # for option_object in search_group:
    #     row = option_object.get_queryset_or_tuple(models.TransactionRecord, request)
    #     search_group_row_list.append(row)
    # # get配置——构建搜索条件
    # conn = get_search_group_condition(search_group, request)

    keyword = request.GET.get('keyword', "").strip()
    con = Q()
    if keyword:
        con.connector = 'OR'
        con.children.append(('order_oid__contains', keyword))
    queryset = models.TransactionRecord.objects.filter(con).filter(**search_group.get_condition).filter(
        customer_id=request.nb_user.id,
        active=1).order_by(
        '-id')

    pager = Pagination(request, queryset)
    context = {
        "pager": pager,
        "keyword": keyword,
        "search_group": search_group
    }
    return render(request, 'my_transaction_list.html', context)


def transaction_list(request):
    # 配置

    search_group = NbSearchGroup(request, models.TransactionRecord, Option('charge_type'))  # choice
    # 也可以 Option('charge_type', is_multi=True, text_func=lambda x: x[1], value_func=lambda x: x[0]),  # choice
    # Option('customer', db_condition={'active': 1}, text_func=lambda x: x.username,
    #        value_func=lambda x: x.id),  # foreignkey

    # search_group_row_list = []
    # for option_object in search_group:
    #     row = option_object.get_queryset_or_tuple(models.TransactionRecord, request)
    #     search_group_row_list.append(row)
    # # get配置——构建搜索条件
    # conn = get_search_group_condition(search_group, request)

    keyword = request.GET.get('keyword', "").strip()
    con = Q()
    if keyword:
        con.connector = 'OR'
        con.children.append(('order_oid__contains', keyword))
        con.children.append(('customer__username__contains', keyword))
    queryset = models.TransactionRecord.objects.filter(con).filter(**search_group.get_condition).filter(
        active=1).order_by('-id')
    pager = Pagination(request, queryset)

    context = {
        "pager": pager,
        "keyword": keyword,
        "search_group": search_group
    }
    return render(request, 'transaction_list.html', context)
